package com.ccx.library.module.login.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ccx.library.config.WechatConfig;
import com.ccx.library.exception.FreezeException;
import com.ccx.library.exception.LoginException;
import com.ccx.library.function.annotation.Permmission;
import com.ccx.library.module.login.service.LoginService;
import com.ccx.library.module.user.entity.User;
import com.ccx.library.response.R;
import com.ccx.library.util.CheckoutUtil;
import io.swagger.annotations.Api;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@Api(tags = "登录")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @ResponseBody
    @Permmission(value = "admin:Core:login")
    @PostMapping("/login")
    public R Login(@RequestBody User user) throws FreezeException, LoginException {
        return R.SUCCESS(loginService.Login(user));
    }

    @Value("${wxcode.appId}")
    private String appId;
    @Value("${wxcode.appSecret}")
    private String appSecret;

    @ResponseBody
    @GetMapping("/wx/auth")
    public R Auth(String signature){
        System.out.println(signature);
        return R.SUCCESS(signature);
    }

    public String getAccess(){
        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&" +
                "secret={1}";
        String newUrl = url.replace("{0}", appId).replace("{1}", appSecret);
        String res = HttpUtil.get(newUrl);
        Map map = (Map) JSON.parse(res);
        System.out.println(map.get("access_token"));
        return (String) map.get("access_token");
    }


    public String getStartURLToGetCode(String code)  {
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=ACCESS_TOKEN";
        String newUrl = url.replace("ACCESS_TOKEN", code);
        return newUrl;
    }

    /**
     * 生成二维码
     * @return
     */
    @ResponseBody
    @RequestMapping("/wx/CreateQR")
    public R doVx() {
        String url = getStartURLToGetCode(getAccess());
        String str = "{\"action_name\":\"QR_LIMIT_SCENE\",\"action_info\":{\"scene\":{\"scene_id\":12}}}";
        String res = HttpUtil.post(url, str);
        Map parse = (Map) JSONObject.parse(res);
        String ticket = (String) parse.get("ticket");
        return R.SUCCESS("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket);
    }

    // 调用微信授权接口重定向
    @GetMapping("/wx/redirect")
    public String toRedirectUrl(HttpServletResponse response) {
        String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize" +
                "?appid=" + appId +
                "&redirect_uri=" + URLEncoder.encode("https://q5b2251925.51vip.biz/library/api/wx/callback") +
                "&response_type=code" + "&scope=snsapi_userinfo" +
                "&state=STATE" + "&connect_redirect=1#wechat_redirect";
        try {
            response.sendRedirect(redirectUrl); // 重定向url
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "重定向成功";
    }

    // 授权接口重定向回调方法
    @GetMapping("/wx/callback")
    public R redirectInfo(@RequestParam(value = "code") String code,
                                             @RequestParam(value = "state", required = false) String state,
                                             HttpServletResponse response) {
        String username = ""; // 微信用户名
        try {
            // 第二步：通过code获取access_token和openid
            String getAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=" + appId +
                    "&secret=" + appSecret +
                    "&code=" + code +
                    "&grant_type=authorization_code";
            String accessTokenRes = HttpUtil.get(getAccessTokenUrl);
            System.out.println("accessTokenRes=>" + accessTokenRes);
            String accessToken = (String) JSON.parseObject(accessTokenRes).get("access_token");
            String openid = (String) JSON.parseObject(accessTokenRes).get("openid");

            // 第四步：通过access_token和openid获取到用户信息
            String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=" + accessToken +
                    "&openid=" + openid +
                    "&lang=zh_CN";
            String userInfoRes = HttpUtil.get(getUserInfoUrl);
            WxUserInfo userInfo = JSON.parseObject(userInfoRes, WxUserInfo.class); // 获取到了微信用户信息
            username = userInfo.getNickname(); // 获取微信用户名
            // TODO 微信用户注册并登录逻辑
            System.out.println(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.SUCCESS(" 用户:" + username + "登录成功！");
    }
}

@Data
class WxUserInfo {
    private String openid;
    private String nickname;
    private Integer sex;
    private String language;
    private String city;
    private String province;
    private String country;
    private String headimgurl;
}
